<?php

namespace xing\ace\logic;

use xing\ace\helper\TreeHelper;
use xing\ace\models\AdminRole;
use xing\ace\models\AdminRule;

class AdminRuleLogic
{

    // 菜单键名设置
    public static $menuKeyMap = [
        'id' => 'id',
        'label' => 'label',
        'url' => 'url',
        '_level' => '_level',
        'items' => 'items',
    ];

    public static function getNav($roleId)
    {
        $AdminRule = AdminRule::find()->where(['pid' => 0, 'status' => 1, 'is_show' => 1, 'type' => [1, 3]]);
        $AdminRule->orderBy(['order' => SORT_DESC]);
        $rules = [];
        if (AdminRole::ADMIN_ID != $roleId) {
            $ids = explode(',', $roleId);
            $roles = AdminRole::find()->where(['id' => $ids])->select(['rule'])->asArray()->all();
            $rules = [];
            foreach ($roles as $role) {
                $rules = array_merge($roles, explode(',', $role['rule']));
            }
            $AdminRule->andWhere(['id' => $rules]);
        }
        $list = $AdminRule->all();

        $navs = [];
        foreach ($list as $v) {
            $navs[] = static::data2array($v, $rules);
        }
        return $navs;
    }

    private static function getChilNav($parentId, $rules, $level = 1)
    {
        if (is_null($parentId)) return [];
        $list = AdminRule::readList($parentId, $rules);
        $navs = [];
        foreach ($list as $v) {
            $navs[] = static::data2array($v, $rules, $level);
        }
        return $navs;
    }

    private static function data2array(AdminRule $adminRule, $rules, $level = 1)
    {
        $return = [
            static::$menuKeyMap['id'] => $adminRule->id,
            static::$menuKeyMap['label'] => $adminRule->title,
            static::$menuKeyMap['url'] => $adminRule->route,
            static::$menuKeyMap['_level'] => $level,
            'condition' => $adminRule->condition,
            'icon' => $adminRule->icon,
        ];
        $nav = static::getChilNav($adminRule->id, $rules, $level + 1);
        if ($nav) $return[static::$menuKeyMap['items']] = $nav;
        return $return;
    }
}
